package com.banshuibao.bsb_android.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.banshuibao.bsb_android.Constants;
import com.banshuibao.bsb_android.MyApplication;
import com.banshuibao.bsb_android.R;
import com.banshuibao.bsb_android.http.HttpResponse;
import com.banshuibao.bsb_android.http.HttpUtil;
import com.banshuibao.bsb_android.model.LoginModel;
import com.banshuibao.bsb_android.util.DataSet;
import com.banshuibao.bsb_android.util.GetLoginInfo;
import com.banshuibao.bsb_android.util.IntentManager;
import com.banshuibao.bsb_android.util.MD5;
import com.banshuibao.bsb_android.util.XToast;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LoginActivity extends BaseActivity implements View.OnClickListener {

    private EditText mPhoneNumber;
    private EditText mPassWord;
    private TextView mRegister, findPassword;
    private Button login_btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initView();
        MyApplication.applicationInstance.removeAlias(GetLoginInfo.getLoginInfoInstance(this).readUser().getUserId());
        MyApplication.applicationInstance.deleteTag("tax","user","1","0");
        GetLoginInfo.getLoginInfoInstance(this).clearInfo();
    }

    private void initView() {
        setTitleText("登录");
        mPhoneNumber = (EditText) findViewById(R.id.register_phoneNumber);
        mPassWord = (EditText) findViewById(R.id.register_password);
        mRegister = (TextView) findViewById(R.id.my_register);
        findPassword = findViewById(R.id.find_password);
        login_btn = (Button) findViewById(R.id.login_btn);
        mRegister.setOnClickListener(this);
        findPassword.setOnClickListener(this);
        login_btn.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.my_register:
                startActivity(new Intent(this, RegisterActivity.class));
                break;
            case R.id.find_password:
                startActivity(new Intent(this, FindPasswordActivity.class));
                break;
            case R.id.login_btn:
                String phoneNumber = mPhoneNumber.getText().toString().trim();
                String password = mPassWord.getText().toString().trim();
                if (isPhone(phoneNumber) && isPassword(password)) {
                    try {
                        showProgressDialog();
                        setLoginPost(phoneNumber, password);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    XToast.showToast(this, "手机号或密码错误");
                }
                break;
        }
    }

    private void setLoginPost(String phoneNumber, String password) throws Exception {
        LoginModel.Body loginModel = new LoginModel.Body();
        loginModel.setPhone(phoneNumber);
        loginModel.setPwd(MD5.encryptMD5ToString(password.getBytes()));
        loginModel.setDeviceType(1);
        HttpUtil.doPost(Constants.Url.LOGIN, loginModel, new HttpResponse(this, LoginModel.class) {
            @Override
            public void onResult(Object obj) {
                LoginModel s = (LoginModel) obj;
//                LogUtil.e(s);
                LoginModel.DataBean data = s.getData();
                MyApplication.applicationInstance.setAlias(data.getUuid());
                String role = data.getRole();
                String type = "";
                if (role.equals("2") || role.equals("3") || role.equals("4")) {
                    type = "tax";
                } else {
                    type = "user";
                }
                MyApplication.applicationInstance.addTag("1", type);
                cancelProgressDialog();
                saveLoginInFo(data);
                finish();
            }

            @Override
            public void responseEnd() {
                super.responseEnd();
                cancelProgressDialog();
            }
        });
    }

    private void saveLoginInFo(LoginModel.DataBean data) {
        SharedPreferences.Editor editor = getSharedPreferences("registerInFo", MODE_PRIVATE).edit();
        editor.putString("cookieId", data.getCookieId());
        editor.putString("headImg", data.getHeadImg());
        editor.putString("firmId", data.getFirmId());
        editor.putString("name", data.getName());
        editor.putString("phoneNumber", data.getPhone());
        editor.putString("role", data.getRole());
        editor.putString("vip", data.getVip());
        editor.putFloat("balance", (float) data.getBalance());
//        editor.putString("",data.getBirthday());
        editor.putLong("vipTime", data.getVipTime());
        editor.putString("position", data.getPositiotn());
        editor.putString("duty", data.getDuty());
        editor.putString("firmName", data.getFirmName());
        editor.putString("userId", data.getUuid());
        editor.putString("rapidLimit", data.getRapidLimit());//是否启用悬赏：0 启用 1 不启用

        editor.commit();
    }

    //点击隐藏输入框之外 隐藏输入框
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    public boolean isPhone(String phone) {
        String repexp = "^[1][345789]\\d{9}";
        Pattern pattern = Pattern.compile(repexp);
        Matcher matcher = pattern.matcher(phone);
        return matcher.matches();
    }

    public boolean isPassword(String password) {
        Pattern pattern = Pattern.compile("[0-9a-zA-Z\\d]{6,15}");
        Matcher matcher = pattern.matcher(password);
        return matcher.matches();
    }

    @Override
    public void finish() {
        super.finish();
        DataSet.clear();
        IntentManager.goUserHomeActivity(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
